package com.handpay.zztong.hp.paymentbill.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.SecureManager;
import com.handpay.framework.notice.ApiNoticeFactory;
import com.handpay.framework.notice.ApiNoticeListener;
import com.handpay.framework.swiper.ApiSwiperFactory;
import com.handpay.framework.utils.BitmapLoader;
import com.handpay.framework.utils.BitmapLoader.ImageCallback;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.DateUtils;
import com.handpay.framework.utils.MyAsyncTask;
import com.handpay.zztong.hp.AppealActivity;
import com.handpay.zztong.hp.GfFoundIndex;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.RescissionActivity;
import com.handpay.zztong.hp.SignatureActivity;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.paymentbill.model.Bill;
import com.handpay.zztong.hp.bean.PurchaseStatus;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.main.fragment.ReceivablesFragment;
import com.handpay.zztong.hp.paymentbill.model.SignTransImage;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.swiper.activity.ConnectSwiperActivity;
import com.handpay.zztong.hp.ui.DialogFactory;
import com.handpay.zztong.hp.ui.TextViewTTF;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.utils.BitmapUtil;

import java.io.ByteArrayInputStream;
import java.lang.ref.WeakReference;
import java.util.Hashtable;
import java.util.zip.CRC32;

import cn.koalsc.btclient.SwipeCardController;
import se.krka.kahlua.vm.LuaTable;

public class TransResultSuccessActivity extends ZZTongActivity implements ApiNoticeListener {

    private ImageView ivSignature;

    private Button revokeButton;
    private Button resignButton;
    private Button mOkBtn;
    private Button mAppealBtn;
    private Bill mBill;
    public static final int REQUEST_SIGNATURE = 1, REQUEST_APPEAL = 2;
    // 在交易结果和交易记录详情的时候，都会保存签名的图片。但请注意这个值有可能没取到，会为空
    protected Bitmap signatureBitmap;
    private byte[] signatureBytes;
    private ScrollView mScrollView;
    private String mPhone;
    private CRC32 mCrc32;
    private View transResult;

    private ViewGroup ll_success_result;// 保存交易成功后的图片，包含交易状态
    private boolean isUploadFile = false;

    private int mPayType;// 获取收款界面的支付方式
    //    private boolean isHideState = false;
    private Button supplementButton;
    private ImageView mDetailImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_trans_result_success);
        this.mAction = getIntent().getByteExtra(ACTION, Action_QueryBills);
        super.onCreate(savedInstanceState);
        this.mBill = (Bill) getIntent().getSerializableExtra(QueryBillsActivity.billvalue);
        mPayType = this.getIntent().getIntExtra(PAYTYPE, 0);// 获取支付方式
        initView();
        ApiNoticeFactory.getInstance().registerApiNoticeListener(this);
    }

    public void initView() {
        mCrc32 = new CRC32();
        mScrollView = (ScrollView) this.findViewById(R.id.mScrollView);
        LinearLayout layout;
        if (mBill.getTradeType() == Bill.TRAD_TYPE_POSPAY) {
            layout = getUniPayView();
        } else {
            layout = getWebPayView();
        }
        if (Action_Transfer1 == mAction || Action_MARKET == mAction) {
            layout.findViewById(R.id.signature_container).setOnClickListener(this);
            ivSignature.setOnClickListener(this);
            layout.findViewById(R.id.resignButton).setVisibility(View.GONE);
        } else if (Action_QueryBills == mAction) {
            /**
             public static final int SHOW_SIGN_STATUS_EXIST_BILL = 1;//有签购单图片
             public static final int SHOW_SIGN_STATUS_NO_BILL = 2;   //无签购单图片；
             public static final int SHOW_SIGN_STATUS_NO_IMAGE = 3;  //noimage不需要补签的交易；
             */
            if (mBill.getShowSignStatus() != Bill.SHOW_SIGN_STATUS_NO_BILL) {
                if (mBill.getShowSignStatus() == Bill.SHOW_SIGN_STATUS_NO_IMAGE) {
                    layout.findViewById(R.id.resignButton).setVisibility(View.GONE);
                } else {
                    mDetailImageView = (ImageView) layout.findViewById(R.id.iv_detail);
                    if (mBill.getTradeType() == Bill.TRAD_TYPE_WEIPAY || mBill.getTradeType() == Bill.TRAD_TYPE_ALIPAY || mBill.getTradeType() == Bill.TRAD_TYPE_WEIPAY_SCAN) {
                        mDetailImageView.setVisibility(View.GONE);//第三方支付没有签名，没有必要去加载图片(服务器自动生成的空白签名图片)
                    } else {
                        mDetailImageView.setVisibility(View.VISIBLE);
                        layout.findViewById(R.id.transactiondetails).setVisibility(View.GONE);
//                        BitmapLoader.getInstance(this).asynLoadBitmap(detailUri, detailUri, new MyImageCallback(ivDetail, TransResultSuccessActivity.this), false);
                        Hashtable<String, String> params = new Hashtable<String, String>();
                        params.put("transSN", mBill.getTransSN()); // 交易流水
                        params.put("transTime", mBill.getTransTime()); // 交易时间
                        this.doJsonPost(this, Do_GetSignTransImage, SignTransImage.class, params);
                    }
                    layout.findViewById(R.id.resignButton).setVisibility(View.GONE);
                    layout.findViewById(R.id.tv_signature_hints).setVisibility(View.INVISIBLE);
                }
            } else {
                if (mBill.getTradeType() == Bill.TRAD_TYPE_WEIPAY || mBill.getTradeType() == Bill.TRAD_TYPE_ALIPAY || mBill.getTradeType() == Bill.TRAD_TYPE_WEIPAY_SCAN) {
                    layout.findViewById(R.id.backButton).setVisibility(View.VISIBLE);
                    layout.findViewById(R.id.backButton).setOnClickListener(this);
                    mOkBtn.setVisibility(View.GONE);
                } else if (mBill.getTradeType() == Bill.TRAD_TYPE_NO_CARD_PAY) {
                    layout.findViewById(R.id.resignButton).setVisibility(View.GONE);
                } else {
                    layout.findViewById(R.id.resignButton).setVisibility(View.VISIBLE);
                    layout.findViewById(R.id.resignButton).setOnClickListener(this);
                }
            }
            mOkBtn.setVisibility(View.GONE);//扫码支付详情页面隐藏完成按钮
        }
    }

    /**
     * 检测交易银行卡照片是否审核通过，不通过则显示重拍按钮
     */
    private void checkSupplementBtnVisibility() {
        if (Action_QueryBills == mAction && !isUploadFile) {
            int isOpen = mBill.getIsOpen();
            String imageUrl = mBill.getCardImageUrl();
            if (isOpen == 1 && TextUtils.isEmpty(imageUrl)) {
                supplementButton.setVisibility(View.VISIBLE);
                return;
            }
        }
        supplementButton.setVisibility(View.GONE);
        // 上传成功清空文件缓存文件夹
        BitmapUtil.deleteICImgsdir();
    }

    /***
     * 银联支付成功后的界面
     *
     * @return
     */
    private LinearLayout getUniPayView() {
        LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.layout_trans_unipay_successed_bill, null);
        mScrollView.addView(layout);
        ((TextView) layout.findViewById(R.id.businessInformation)).setText(mBill.getShopName());
        ((TextView) layout.findViewById(R.id.business_no)).setText(mBill.getMerchantCode());
        String transferCardNo;
        if (TextUtils.isEmpty(mBill.getTranMediaType())) {
            transferCardNo = mBill.getCardNoOut();
        } else {
            transferCardNo = mBill.getCardNoOut() + " /" + mBill.getTranMediaType();
        }
        ((TextView) layout.findViewById(R.id.transfer_card_no)).setText(transferCardNo);
        supplementButton = (Button) layout.findViewById(R.id.supplementButton);
        supplementButton.setOnClickListener(this);
        checkSupplementBtnVisibility();
        ((TextViewTTF) layout.findViewById(R.id.txn_type)).setText(R.string.account_transfer);
        ((TextView) layout.findViewById(R.id.batch_no)).setText(mBill.getTransSN());
        ((TextView) layout.findViewById(R.id.date_time)).setText(DateUtils.formatDateToString(DateUtils.formatStringToDate(mBill.getTransTime(), "yyyyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss"));
        ((TextView) layout.findViewById(R.id.amount_no)).setText(CommonUtils.formatMoney(mBill.getAmount() / 100));
        ll_success_result = (ViewGroup) layout.findViewById(R.id.ll_success_result);
        ivSignature = (ImageView) layout.findViewById(R.id.iv_signature);
        transResult = layout.findViewById(R.id.transactiondetails);
        revokeButton = (Button) layout.findViewById(R.id.revokeButton);
        revokeButton.setOnClickListener(this);
        if (Action_Transfer2 == mAction || Action_Transfer1 == mAction) {
            revokeButton.setVisibility(View.GONE);
        } else {
            // tIsRevoke :是否可以撤销 1表示可以 0表示不可以
            // RovokeState: 0 未撤销；1已撤销；2撤销中；3撤销失败
            // 隐藏按钮调 IsRevoke==0 或者 RovokeState==1 / 2
            if (mBill.getIsRevoke() == 0 || (mBill.getRovokeState() == Bill.STATES_ROVOKE_ING || mBill.getRovokeState() == Bill.STATES_ROVOKE_SUCCESS)) {
                revokeButton.setVisibility(View.GONE);
            }
        }
        // mPrintBtn = (Button) layout.findViewById(R.id.printButton);
        // mPrintBtn.setVisibility(View.VISIBLE);
        // mPrintBtn.setOnClickListener(this);
        resignButton = (Button) layout.findViewById(R.id.resignButton);
        resignButton.setVisibility(View.VISIBLE);
        resignButton.setOnClickListener(this);
        // 签名点击区域
        layout.findViewById(R.id.signature_container).setOnClickListener(this);
        ivSignature.setOnClickListener(this);
        mOkBtn = (Button) layout.findViewById(R.id.nextButton);
        mAppealBtn = (Button) layout.findViewById(R.id.appealButton);
        mAppealBtn.setOnClickListener(this);
        return layout;
    }

    /***
     * 第三方支付成功后的界面
     *
     * @return
     */
    private LinearLayout getWebPayView() {
        LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.layout_trans_webpay_successed_bill, null);
        mScrollView.addView(layout);
        ImageView transaction_image = (ImageView) layout.findViewById(R.id.transaction_image);
        TextView transaction_ScanAmount = (TextView) layout.findViewById(R.id.transaction_ScanAmount);
        TextView transaction_MerchatAccount = (TextView) layout.findViewById(R.id.transaction_MerchatAccount);
        TextView transaction_MerchatSn = (TextView) layout.findViewById(R.id.transaction_MerchatSn);
        TextView transaction_RecordTime = (TextView) layout.findViewById(R.id.transaction_RecordTime);
        TextView transaction_ConsumptionAccount = (TextView) layout.findViewById(R.id.transaction_ConsumptionAccount);
        TextView transaction_RecordNumber = (TextView) layout.findViewById(R.id.transaction_RecordNumber);
        TextViewTTF transaction_OrderName = (TextViewTTF) layout.findViewById(R.id.transaction_OrderName);
        TextView transaction_OrderNumber = (TextView) layout.findViewById(R.id.transaction_OrderNumber);
        ivSignature = (ImageView) layout.findViewById(R.id.iv_signature);
        RelativeLayout tr_orderno = (RelativeLayout) layout.findViewById(R.id.tr_orderno);
        layout.findViewById(R.id.signature_container).setVisibility(View.GONE);
        // 温馨提示
        TextView trans_tip = (TextView) layout.findViewById(R.id.trans_tips);
        if (mBill.getTradeType() == Bill.TRAD_TYPE_ALIPAY) {
            trans_tip.setText(R.string.traderesult_tip);
            transaction_OrderName.setText(getString(R.string.trans_alipay_order_name));
        } else if (mBill.getTradeType() == Bill.TRAD_TYPE_WEIPAY || mBill.getTradeType() == Bill.TRAD_TYPE_WEIPAY_SCAN) {
            trans_tip.setText(R.string.traderesult_webpay_tip);
            transaction_OrderName.setText(getString(R.string.trans_wxpay_order_name));
        }
        trans_tip.setVisibility(View.GONE);// 成功之后提示信息不显示
        transResult = layout.findViewById(R.id.transactiondetails);
        ll_success_result = (ViewGroup) layout.findViewById(R.id.ll_success_result);
        // 撤销
        revokeButton = (Button) layout.findViewById(R.id.revokeButton);
        revokeButton.setOnClickListener(this);
        if (Action_Transfer2 == mAction || Action_Transfer1 == mAction) {
            revokeButton.setVisibility(View.GONE);
        } else {
            // tIsRevoke :是否可以撤销 1表示可以 0表示不可以
            // RovokeState: 0 未撤销；1已撤销；2撤销中；3撤销失败
            // 隐藏按钮调 IsRevoke==0 或者 RovokeState==1 / 2
            if (mBill.getIsRevoke() == 0 || (mBill.getRovokeState() == Bill.STATES_ROVOKE_ING || mBill.getRovokeState() == Bill.STATES_ROVOKE_SUCCESS)) {
                revokeButton.setVisibility(View.GONE);
            }
        }
        /***
         * transaction_image.setBackgroundResource（）方法会出现图片被压缩
         * 解决方法设置为transaction_image.setImageResource（）
         */
        if (mBill.getTradeType() == Bill.TRAD_TYPE_ALIPAY) {
            transaction_image.setImageResource(R.drawable.traderesult_alipay_icon);
        } else if (mBill.getTradeType() == Bill.TRAD_TYPE_WEIPAY || mBill.getTradeType() == Bill.TRAD_TYPE_WEIPAY_SCAN) {
            transaction_image.setImageResource(R.drawable.traderesult_weipay_icon);
        } else {
            transaction_image.setImageResource(R.drawable.unionpay_icon);
        }
        transaction_ScanAmount.setText(CommonUtils.formatMoney(mBill.getAmount() / 100));
        transaction_MerchatAccount.setText(mBill.getShopName());
        transaction_MerchatSn.setText(mBill.getMerchantCode());
        transaction_RecordTime.setText(DateUtils.formatDateToString(DateUtils.formatStringToDate(mBill.getTransTime(), "yyyyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss"));
        String transferCardNo;
        if (TextUtils.isEmpty(mBill.getTranMediaType())) {
            transferCardNo = mBill.getCardNoOut();
        } else {
            transferCardNo = mBill.getCardNoOut() + " /" + mBill.getTranMediaType();
        }
        if (!TextUtils.isEmpty(mBill.getTransAccount())) {
            // 消费账户
            transaction_ConsumptionAccount.setText(CommonUtils.formattingCard_4(mBill.getTransAccount()));
        }
        transaction_RecordNumber.setText(mBill.getTransSN());
        // 订单号
        if (mBill.getTradeType() == Bill.TRAD_TYPE_ALIPAY || mBill.getTradeType() == Bill.TRAD_TYPE_WEIPAY || mBill.getTradeType() == Bill.TRAD_TYPE_WEIPAY_SCAN) {
            tr_orderno.setVisibility(View.VISIBLE);
            transaction_OrderNumber.setText(mBill.getOrderNo());
        }
        // 签名点击区域
        layout.findViewById(R.id.signature_container).setOnClickListener(this);
        ivSignature.setOnClickListener(this);
        resignButton = (Button) layout.findViewById(R.id.resignButton);
        // 手机端只显示完成按钮
        mOkBtn = (Button) layout.findViewById(R.id.nextButton);
        mAppealBtn = (Button) layout.findViewById(R.id.appealButton);
        mAppealBtn.setOnClickListener(this);
        mOkBtn.setVisibility(View.VISIBLE);
        mOkBtn.setOnClickListener(this);
        return layout;
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 进入以后，拖动到最下面
        mScrollView.postDelayed(new Runnable() {
            @Override
            public void run() {
                mScrollView.smoothScrollTo(0, mScrollView.getHeight());
            }
        }, 200);

    }

    @Override
    protected boolean isShownTopBar() {
        return true;
    }

    @Override
    public ActionBar getActivityActionBar() {
        if (Action_QueryBills == mAction) {
            return new ActionBar(this.getString(R.string.trans_result_detial), true, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        } else {
            return new ActionBar(this.getString(R.string.trans_result_confirm));
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.signature_container || i == R.id.iv_signature) {
            if (signatureBitmap == null) {
                goToSignature();
            }
        } else if (i == R.id.revokeButton) {
            gotoRevoktrade();
        } else if (v.getId() == R.id.backButton) {
            // 如果是流水查询页面来的点击直接返回
            if (Action_QueryBills == mAction) {
                this.setResult(1);
                finish();
            } else {
                // 打印
                checkSwiperAndPrintBill(null);
            }
        } else if (i == R.id.nextButton) {
            if (mBill.getTradeType() == Bill.TRAD_TYPE_POSPAY) {
                saveSignature(signatureBytes, mPhone);
            } else {
                finish();
            }
            // 打印
            // checkSwiperAndPrintBill(null);
        } else if (i == R.id.resignButton) {
            goToSignature();
        } else if (i == R.id.supplementButton) {
            if (mBill != null && TextUtils.isEmpty(mBill.getCardImageUrl())) {
                showTipCamera(false);
            }
        } else if (i == R.id.appealButton) {
            goToAppeal();
        }
    }

    private void goToAppeal() {
        Intent intent = new Intent(this, AppealActivity.class);
        intent.putExtra(ACTION, mBill);
        this.startActivityForResult(intent, REQUEST_APPEAL);
    }

    private void goToSignature() {
        Intent i = new Intent(this, SignatureActivity.class);
        i.putExtra(ATProtocolConstant.AMOUNT_KEY, mBill.getAmount());
        i.putExtra(ACTION, mBill.getTradeType());
        this.startActivityForResult(i, REQUEST_SIGNATURE);
    }

    private void gotoRevoktrade() {
        Intent revok_intent = new Intent(this, RescissionActivity.class);
        revok_intent.putExtra(QueryBillsActivity.billvalue, mBill);
        startActivity(revok_intent);
    }

    // 检查刷卡器---打印
    void checkSwiperAndPrintBill(final Runnable runnable) {
        if (checkVPOS(this, true)) {
            // 如果该刷卡器支持
            if (ApiSwiperFactory.getInstance().isSupportPrint()) {
                // 准备调用打印功能
                printBill(runnable);
            } else {
                // 提醒用户切换刷卡器
                this.showAlertDialog(this, getString(R.string.tip), getString(R.string.not_support_print_swiper), true, getString(R.string.dialog_choose_swiper), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(TransResultSuccessActivity.this, ConnectSwiperActivity.class));
                        dialog.dismiss();
                    }
                }, getString(R.string.cancel_printed), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (null != runnable) {
                            runnable.run();
                        } else {
                            goBack();
                        }
                        dialog.dismiss();
                    }
                }, null, null);
            }
        }
    }

    @Override
    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert) {
        boolean bResult = super.netJsonResponse(action, resp, showAlert);
        if (bResult) {
            return true;
        }
        if (Do_UploadSig.equals(action)) {
            if (0 == CommonUtils.objectToInt(resp.getResponseCode())) {
                finish();
            } else {
                findViewById(R.id.signature_container).setClickable(true);
                this.showAlertDialog(this, getString(R.string.tip), getString(R.string.save_fail), true, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        saveSignature(signatureBytes, mPhone);
                        dialog.dismiss();
                    }
                }, null);
            }
            if (ClientEngine.getInstance().getGlobal("guangfa_user_can_buy") != null && ClientEngine.getInstance().getGlobal("guangfa_user_can_buy") instanceof Boolean && (Boolean) ClientEngine.getInstance().getGlobal("guangfa_user_can_buy")) {
                if ((Double) ClientEngine.getInstance().getGlobal("guangfa_firstAmount") / 100 > 0d) {
                    getzztGFPayment((Double) ClientEngine.getInstance().getGlobal("guangfa_firstAmount"));
                }
            }
            return true;
        } else if (Do_GetSignTransImage.equals(action)) {
            SignTransImage bean = (SignTransImage) resp;
            byte bitmapBytes[] = CommonUtils.hexStringToBytes(bean.getSignImage());
            Bitmap bitmap = BitmapUtil.bytes2Bimap(bitmapBytes);
            if (null != bitmap) {
                bitmap = CommonUtils.zoomImg(bitmap, screenWidth);
                transResult.setVisibility(View.GONE);
            } else {
                ImageView ivDetail = (ImageView) findViewById(R.id.iv_detail);
                ivDetail.setVisibility(View.GONE);
                findViewById(R.id.transactiondetails).setVisibility(View.VISIBLE);
            }
            mDetailImageView.setImageBitmap(bitmap);
            return true;
        }
        return true;
    }

    @Override
    public boolean netResponse(String action, final Hashtable<String, Object> resp, boolean showAlert, OnClickListener on) {
        closeProgressDialog();
        if (Do_UploadSig.equals(action)) {
            boolean result = super.netResponse(action, resp, showAlert, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    boolean isNeedRetry = true;
                    byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
                    if (null != data) {
                        LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
                        if ("S364".equals(luaTable.rawget("responseCode"))) {
                            isNeedRetry = false;
                        }
                        if ("S360".equals(luaTable.rawget("responseCode"))) {
                            isNeedRetry = false;
                        }
                    }
                    if (isNeedRetry) {
                        TransResultSuccessActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                saveSignature(signatureBytes, mPhone);
                            }
                        });
                    } else {
                        findViewById(R.id.signature_container).setClickable(false);
                    }
                }
            });
            if (result) {
                findViewById(R.id.signature_container).setClickable(true);
                return true;
            }
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            Double responseCode = CommonUtils.objectToDouble(luaTable.rawget("responseCode"));
            if (0 == responseCode) {
                findViewById(R.id.signature_container).setClickable(false);
                finish();
                // 设置完成按钮可见
                // findViewById(R.id.nextButton).setVisibility(View.VISIBLE);
            } else {
                findViewById(R.id.signature_container).setClickable(true);
                this.showAlertDialog(this, getString(R.string.tip), getString(R.string.save_fail), true, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        saveSignature(signatureBytes, mPhone);
                        dialog.dismiss();
                    }
                }, null);
            }
            if (ClientEngine.getInstance().getGlobal("guangfa_user_can_buy") != null && ClientEngine.getInstance().getGlobal("guangfa_user_can_buy") instanceof Boolean && (Boolean) ClientEngine.getInstance().getGlobal("guangfa_user_can_buy")) {
                if ((Double) ClientEngine.getInstance().getGlobal("guangfa_firstAmount") / 100 > 0d) {
                    getzztGFPayment((Double) ClientEngine.getInstance().getGlobal("guangfa_firstAmount"));
                }
            }
            return true;
        } else if (Do_ZztGFPayment.equals(action)) {
            boolean result = super.netResponse(action, resp, showAlert, on);
            if (result) {
                this.setResult(Activity.RESULT_CANCELED);
                return true;
            }
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            dealPayResult(data);
            return false;
        } else if (Do_ZztGFFundIndex.equals(action)) {
            boolean result = super.netResponse(action, resp, showAlert, on);
            if (result) {
                this.setResult(Activity.RESULT_CANCELED);
                return true;
            }
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            String responseCode = (String) luaTable.rawget("responseCode");
            String errorMessage = (String) luaTable.rawget("errMessage");
            LuaTable chartsTable = (LuaTable) luaTable.rawget("charts");
            if (errorMessage == null && responseCode == null && chartsTable != null) {
                Intent intent = new Intent();
                intent = new Intent(this, GfFoundIndex.class);
                intent.putExtra("indexData", data);
                startActivity(intent);
                finish();
            } else {
                DialogFactory.showAlertDialog(this, getString(R.string.tip), errorMessage != null ? errorMessage : getString(R.string.guangfa_system_error), true);
            }
            return false;
        } else {
            return super.netResponse(action, resp, showAlert, on);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_APPEAL:
                if (Activity.RESULT_OK == resultCode) {
                    this.finish();
                }
                break;
            case REQUEST_SIGNATURE:
                if (Activity.RESULT_OK == resultCode) {
                    if (null != signatureBitmap) {
                        signatureBitmap.recycle();
                        signatureBitmap = null;
                    }
                    byte[] imgBytes = data.getByteArrayExtra("signature");
                    signatureBitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(imgBytes));
                    signatureBytes = imgBytes;
                    HPLog.i(HPLog.YL_TAG, "imgBytes sign length:" + imgBytes.length);
                    HPLog.i(HPLog.YL_TAG, "signatureBitmap size:" + signatureBitmap.getByteCount());
                    if (null != signatureBitmap) {
                        int width = ivSignature.getWidth();
                        int height = ivSignature.getHeight();
                        Bitmap b = Bitmap.createScaledBitmap(signatureBitmap, width, height, false);
                        ivSignature.setImageBitmap(b);
                        findViewById(R.id.tv_signature_hints).setVisibility(View.GONE);
                        mOkBtn.setVisibility(View.VISIBLE);
                        resignButton.setVisibility(View.GONE);
                        mOkBtn.setOnClickListener(this);
                    } else {
                        HPLog.i(HPLog.YL_TAG, "signatureBitmap null");
                        findViewById(R.id.tv_signature_hints).setVisibility(View.VISIBLE);
                        mOkBtn.setVisibility(View.GONE);
                    }
                } else {
                    if (null == signatureBitmap) {
                        findViewById(R.id.tv_signature_hints).setVisibility(View.VISIBLE);
                    }
                }
                if (null != data) {
                    mPhone = data.getStringExtra(BaseProtocolKey.PHONE);
                } else {
                    mPhone = "";
                }
                // 延时去截屏。
                mScrollView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 滑动到底，方面用户看到完成。
                        mScrollView.fullScroll(View.FOCUS_DOWN);
                    }
                }, 200);
                break;
            case ZZTConstant.REQUEST_CAMERA_CODE:
                String fileUrl = null;
                if (resultCode == Activity.RESULT_OK) {
                    // 保存成功

                    if (data != null && data.getStringExtra("FileUrl") != null) {
                        fileUrl = data.getStringExtra("FileUrl");
                        HPLog.e(HPLog.FDL_TAG, "FileUrl" + data.getStringExtra("FileUrl"));
                    }
                    HPLog.e(HPLog.FDL_TAG, "onActivityResult--保存成功 ");
                } else {
                    // 保存失败
                    HPLog.e(HPLog.FDL_TAG, "onActivityResult--保存失败");
                }
                if (TextUtils.isEmpty(fileUrl)) {
                    HPLog.e(HPLog.FDL_TAG, "拍照取消----未返回");
                    return;
                }

                String mPlainAccount = mBill.getCardNoOutFull();
                String transSN = mBill.getTransSN();
                String transTime = mBill.getTransTime();
                String merchantcode = mBill.getMerchantCode();

                if (TextUtils.isEmpty(mPlainAccount) || TextUtils.isEmpty(transTime) || TextUtils.isEmpty(transSN) || TextUtils.isEmpty(merchantcode)) {
                    HPLog.e(HPLog.FDL_TAG, "mPlainAccount  Or " + "transTime Or" + "transSN Or " + "merchantcode isNull");
                    return;
                }
                HPLog.e(HPLog.FDL_TAG, "开始上传");
                upLoadBankCardPic(fileUrl, mPlainAccount, transTime, transSN, merchantcode, null, true, true);
                isUploadFile = true;
                // 是否要返回？
                supplementButton.setVisibility(View.GONE);

        }
    }

    void printBill(final Runnable r) {
        new MyAsyncTask<Void, Void, Boolean>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                showProgressDialog(TransResultSuccessActivity.this, getString(R.string.printting));
            }

            @Override
            protected Boolean doInBackground(Void... params) {
                StringBuffer content1 = new StringBuffer();
                StringBuffer content2 = new StringBuffer();
                if (mBill.getTradeType() == Bill.TRAD_TYPE_POSPAY) {
                    content2.append("\n          " + getResources().getString(R.string.trans_Voucher) + "\n\n").append(getString(R.string.business_information) + "  " + mBill.getShopName() + "\n\n").append(getString(R.string.business_no) + "  " + mBill.getMerchantCode() + "\n\n")
                            // .append(getString(R.string.terminal_no) +
                            // mBill.getTerminalNo() + "\n")
                            // .append(getString(R.string.operator_no) + "\n")
                            .append(getString(R.string.transfer_success_card_no) + "  " + mBill.getCardNoOut() + "\n\n")
                            // .append(getString(R.string.iss_no) +
                            // mBill.getIssId()
                            // + "\n")
                            // .append(getString(R.string.acq_no) +
                            // mBill.getSpecialNumber() + "\n")
                            .append(getString(R.string.txn_type) + "  " + getString(R.string.account_transfer) + "\n\n")
                            // .append(getString(R.string.exp_date) + "\n")
                            .append(getString(R.string.batch_no) + "    " + mBill.getTransSN() + "\n\n")
                            // .append(getString(R.string.voucher_no) + "\n")
                            // .append(getString(R.string.auth_no) + "\n")
                            .append(getString(R.string.date_time) + "  " + DateUtils.formatDateToString(DateUtils.formatStringToDate(mBill.getTransTime(), "yyyyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss") + "\n\n")
                            // .append(getString(R.string.ref_no) + "\n"
                            // .append(getString(R.string.card_org) +
                            // mBill.getCardOrg() + "\n")
                            .append(getString(R.string.amount_no) + "  " + CommonUtils.formatMoney(mBill.getAmount() / 100) + "\n\n");
                } else {
                    // 支付宝微信订单号比较长 截取两段打印
                    String orderno = mBill.getOrderNo();
                    String orderno1 = "";
                    String orderno2 = "";
                    if (orderno.length() > 19) {
                        orderno1 = orderno.substring(0, 19);
                        orderno2 = orderno.substring(20);
                        content2.append("\n          " + getResources().getString(R.string.trans_Voucher) + "\n\n").append(getString(R.string.business_information) + "  " + mBill.getShopName() + "\n\n").append(getString(R.string.business_no) + "  " + mBill.getMerchantCode() + "\n\n").append(getString(R.string.date_time) + "  " + DateUtils.formatDateToString(DateUtils.formatStringToDate(mBill.getTransTime(), "yyyyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss") + "\n\n").append(getString(R.string.txn_type) + "  " + (mBill.getTradeType() == Bill.TRAD_TYPE_ALIPAY ? getString(R.string.trade_alipay) : getString(R.string.trade_weipay)) + "\n\n").append(getString(R.string.transAccount) + "  " + mBill.getTransAccount() + "\n\n").append(getString(R.string.trans_record_number) + "  " + mBill.getTransSN() + "\n\n").append(getString(R.string.trans_order_number) + "    " + orderno1 + "\n\n").append("           " + orderno2 + "\n\n").append(getString(R.string.amount_no) + "    " + CommonUtils.formatMoney(mBill.getAmount() / 100) + "\n\n");
                    } else {// 防止有小于19位的
                        content2.append("\n          " + getResources().getString(R.string.trans_Voucher) + "\n\n").append(getString(R.string.business_information) + "  " + mBill.getShopName() + "\n\n").append(getString(R.string.business_no) + "  " + mBill.getMerchantCode() + "\n\n").append(getString(R.string.date_time) + "  " + DateUtils.formatDateToString(DateUtils.formatStringToDate(mBill.getTransTime(), "yyyyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss") + "\n\n").append(getString(R.string.txn_type) + "  " + (mBill.getTradeType() == Bill.TRAD_TYPE_ALIPAY ? getString(R.string.trade_alipay) : getString(R.string.trade_weipay)) + "\n\n").append(getString(R.string.transAccount) + "  " + mBill.getTransAccount() + "\n\n").append(getString(R.string.trans_record_number) + "  " + mBill.getTransSN() + "\n\n").append(getString(R.string.trans_order_number) + "    " + orderno + "\n\n").append(getString(R.string.amount_no) + "    " + CommonUtils.formatMoney(mBill.getAmount() / 100) + "\n\n");
                    }
                }
                content1.append(content2).append("        " + getString(R.string.transfer_agree_pay) + "\n");

                /**
                 * N900打印
                 */
                // 打印logo
                Bitmap logo = BitmapFactory.decodeResource(getResources(), R.drawable.logo);

                if (false == ApiSwiperFactory.getInstance().printBitMap(110, logo)) {
                    return Boolean.FALSE;
                }

                if (false == ApiSwiperFactory.getInstance().printString(content1.toString())) {
                    return Boolean.FALSE;
                }

                if (signatureBitmap == null) {
                    Bitmap keyboard_number_null = BitmapFactory.decodeResource(getResources(), R.drawable.keyboard_number_null);
                    if (false == ApiSwiperFactory.getInstance().printString("\n\n" + "请持卡人签名:" + "\n\n\n\n\n")) {
                        return Boolean.FALSE;
                    }
                    if (false == ApiSwiperFactory.getInstance().printBitMap(70, imageZoom(keyboard_number_null))) {
                        return Boolean.FALSE;
                    }
                    // 打印空白签名后多打几个空行方便撕小票
                    if (false == ApiSwiperFactory.getInstance().printString("\n\n\n\n")) {
                        return Boolean.FALSE;
                    }
                    // 等待3秒打印第二联
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (false == ApiSwiperFactory.getInstance().printBitMap(110, logo)) {
                        return Boolean.FALSE;
                    }
                    content2.append("\n\n\n\n");
                    if (false == ApiSwiperFactory.getInstance().printString(content2.toString())) {
                        return Boolean.FALSE;
                    }

                    return Boolean.TRUE;
                } else {
                    if (false == ApiSwiperFactory.getInstance().printString("\n\n" + "请持卡人签名:")) {
                        return Boolean.FALSE;
                    }
                    // 打印签名
                    if (false == ApiSwiperFactory.getInstance().printBitMap(70, imageZoom(signatureBitmap))) {
                        return Boolean.FALSE;
                    }
                    // 打印签名后多打几个空行方便撕小票
                    if (false == ApiSwiperFactory.getInstance().printString("\n\n\n\n\n\n")) {
                        return Boolean.FALSE;
                    }
                    // 等待3秒打印第二联
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (false == ApiSwiperFactory.getInstance().printBitMap(110, logo)) {
                        return Boolean.FALSE;
                    }
                    content2.append("\n\n\n\n");
                    if (false == ApiSwiperFactory.getInstance().printString(content2.toString())) {
                        return Boolean.FALSE;
                    }

                    return Boolean.TRUE;
                }
            }

            @Override
            protected void onPostExecute(Boolean result) {
                closeProgressDialog();
                if (true == result.booleanValue()) {
                    Toast.makeText(TransResultSuccessActivity.this, getString(R.string.printed_success), Toast.LENGTH_SHORT).show();
                    finish();
                    if (null != r) {
                        r.run();
                    }
                } else {
                    showAlertDialog(TransResultSuccessActivity.this, getString(R.string.tip), getString(R.string.printed_failed), false, getString(R.string.retry_printed), new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            printBill(r);
                        }
                    }, getString(R.string.cancel_printed), new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // if (null != r) {
                            // r.run();
                            // }
                            goBack();
                        }
                    }, null, null);
                }
            }

            @Override
            protected void onCancelled(Boolean result) {
                super.onCancelled();
                closeProgressDialog();
            }
        }.execute();
    }

    /**
     * 图片缩放
     *
     * @param bitmap
     */
    public Bitmap imageZoom(Bitmap bitmap) {
        // 获取这个图片的宽和高
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        // 定义预转换成的图片的宽度和高度
        int newWidth = 250;
        int newHeight = 150;

        // 计算缩放率，新尺寸除原始尺寸
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();

        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);

        // 创建新的图片
        return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    }

    /**
     * 保存签购单图片
     *
     * @param sigByte
     * @param phone
     */
    private void saveSignature(byte[] sigByte, String phone) {
        findViewById(R.id.signature_container).setClickable(false);
        findViewById(R.id.resignButton).setVisibility(View.GONE);
        showProgressDialog(this, getResources().getString(R.string.pleasewait));
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        String sig;
        String sigCheck;
        if (!TextUtils.isEmpty(phone)) {
            params.put(BaseProtocolKey.PHONE, SecureManager.getInstance().des(phone, 1, null));
        }
        sig = CommonUtils.bytesToHexString(sigByte);
        sigCheck = CommonUtils.getCRC(mCrc32, sigByte);
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
        params.put("sign", sig);
        params.put("signCheck", sigCheck);
        // Bitmap billBitmap = transResult.getDrawingCache();
        Bitmap billBitmap = ll_success_result.getDrawingCache();
        byte[] billTransferByte;
        if (null == billBitmap) {
            // drawCache not work. use view.draw
            HPLog.i(HPLog.LFP_TAG, "getDrawingCache not work!");
            // View result = transResult;
            View result = ll_success_result;
            billBitmap = Bitmap.createBitmap(result.getWidth(), result.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas cv = new Canvas(billBitmap);
            result.draw(cv);
             billTransferByte = CommonUtils.resizeImage(billBitmap, screenWidth);
            billBitmap. recycle();
        } else {
            billTransferByte = CommonUtils.resizeImage(billBitmap, screenWidth);
        }
        if (null != billTransferByte && 0 != billTransferByte.length) {
            //
            String billBitmapStr = CommonUtils.bytesToHexString(billTransferByte);
            params.put("bill", billBitmapStr);
            params.put("billCheck", CommonUtils.getCRC(mCrc32, billTransferByte));
            params.put("transTime", mBill.getTransTime());
            params.put("transSN", mBill.getTransSN());
            if (Action_QueryBills == mAction) {
                HPLog.e(HPLog.FDL_TAG, "Do_UploadSig----isRepair =1");
                params.put("isRepair", "1");
            }
            this.doJsonPost(this, Do_UploadSig, ResponseBean.class, params);
        } else {
            HPLog.e(HPLog.LFP_TAG, "Cannot get bill bitmap!");
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mAction == Action_QueryBills) {
                finish();
            }
        }
        return true;
    }

    /**
     * 获取基金申购 传入的参数是分为单位
     */
    private void getzztGFPayment(Double amountApply) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put(BaseProtocolKey.PRODUCTCODE, "HLC");
        String amountString = "" + Math.round(amountApply);
        params.put("amount", SecureManager.getInstance().des(amountString, 1, null));
        this.doPost(this, Do_ZztGFPayment, params);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String pageUrl = getIntent().getStringExtra("pageUrl");
        if (!TextUtils.isEmpty(pageUrl)) {
            Bundle bundle = new Bundle();
            bundle.putString("pageUrl", pageUrl);
            bundle.putString("status", "1");
            ApiNoticeFactory.getInstance().doBroadCastNotice(ApiNoticeListener.MARKET_ACTION, bundle);
        }
        ApiNoticeFactory.getInstance().unregisterApiNoticeListener(this);
    }

    @Override
    public void goToVPos() {
        super.goToVPos();
        checkSwiperAndPrintBill(null);
    }

    private void goToGuangfaIndex() {
        // 先去请求数据,根据返回的数据，再跳转。
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put(BaseProtocolKey.PRODUCTCODE, "HLC");
        doPost(this, Do_ZztGFFundIndex, params, true);
    }

    // 处理购买广发的结果
    private void dealPayResult(byte[] data) {
        ClientEngine.getInstance().saveGlobal("guangfa_user_can_buy", false);// 清空标记，防止误发。
        ClientEngine.getInstance().saveGlobal("guangfa_firstAmount", 0d);// 清空金额。
        LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
        LuaTable purchase = (LuaTable) luaTable.rawget("purchaseStatus");
        PurchaseStatus purchaseStatus = PurchaseStatus.generatePurchaseStatus(purchase);
        if (purchaseStatus != null) {
            if (purchaseStatus.getStatus() != null) {
                if ("WW".equals(purchaseStatus.getStatus()) || "00".equals(purchaseStatus.getStatus())) {
                    showAlertDialog(this, getString(R.string.guangfa_auto_buy_success), "金额:" + CommonUtils.formatMoneyDouble(Double.parseDouble(purchaseStatus.getAmount() + "") / 100) + "元", false, "好的知道了", new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            arg0.dismiss();

                        }
                    }, getString(R.string.guagnfa_goto_detail_now), new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            goToGuangfaIndex();
                        }
                    }, null, null);
                } else if ("W1".equals(purchaseStatus.getStatus()) || "01".equals(purchaseStatus.getStatus()) || "02".equals(purchaseStatus.getStatus())) {
                    showAlertDialog(this, getString(R.string.guangfa_auto_buy_fail), "金额:" + CommonUtils.formatMoneyDouble(Double.parseDouble(purchaseStatus.getAmount() + "") / 100) + "元" + "\n" + "失败原因:" + purchaseStatus.getMessage(), false, "好的知道了", new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            arg0.dismiss();

                        }
                    }, getString(R.string.guagnfa_goto_detail_now), new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            goToGuangfaIndex();
                        }
                    }, null, null);
                }
            }
        } else {
            String errorMessage = (String) luaTable.rawget("errMessage");
            showAlertDialog(this, getResources().getString(R.string.tip_title), errorMessage != null ? errorMessage : getString(R.string.guangfa_system_error), false, new OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                }
            });
        }
    }


    @Override
    public void onNotifyNotice(int action, Bundle bundle) {
        finish();
    }

    @Override
    public int[] getNoticeAction() {
        int actions[] = {RESCISSION_ACTION};
        return actions;
    }
}
